package com.fileshare.web.config;

import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.*;

@Configuration
public class AutoSystemConfig implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private RequestMappingHandlerMapping mapping;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        autoLoadCache();
        autoApplyConfig();
        autoScanAndSaveControllerPatterns();
    }

    private void autoLoadCache() {

    }

    private void autoApplyConfig() {

    }

    private void autoScanAndSaveControllerPatterns() {
        Map<String, List<String>> controllerPatterns = new HashMap<>();
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
            HandlerMethod value = entry.getValue();
            RequestMappingInfo key = entry.getKey();
            String controller = value.getBeanType().getSimpleName();
            if (key.getPathPatternsCondition() == null) continue;
            List<String> urls = new ArrayList<>(Objects.requireNonNull(key.getPathPatternsCondition()).getPatternValues());
            controllerPatterns.put(controller, urls);
        }
    }
}